#!/usr/bin/env ruby
OS = 'mac'
$LOAD_PATH << (File.dirname(__FILE__) + '/core/')

require 'optparse'
require 'logger'
require 'cc_monitor'
require 'mac_dashboard_converter'

opts = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} [options]"
  opts.separator ""
  opts.separator "Synopsis:"
  opts.separator "ccm -f 'monitor file uri' interval"
  opts.separator "ccm -i interval"
  opts.separator "ccm -o"
  opts.separator "ccm -s"
  opts.separator "ccm -t"
  opts.separator "ccm -v"
  opts.separator "ccm -u"
  opts.separator "ccm -r"
  opts.separator ""
  opts.separator "Options:"
  
  opts.on("-r", "--running", "get ccms running status") do
    puts "ccms is #{CcMonitor::Service.new.running? ? 'running' : 'stopped'}"
  end
  opts.on("-f", "--file_uri CCM_URI", "write setting of cc monitor uri") do |uri|
    CcMonitor::Service.new.set_uri uri
  end

  opts.on("-i", "--interval [INTERVAL]", "write setting of cc monitor running interval") do |interval|
    CcMonitor::Service.new.set_interval interval
  end

  opts.on("-o", "--output", "get builds status which is cc monitor output") do
    puts MacDashboardConverter.new.convert(CcMonitor::Service.new.output)
  end

  opts.on("-s", "--start", "start cc monitor service") do
    CcMonitor::Service.new.start
  end
  
  opts.on("-t", "--stop", "stop cc monitor service") do
    CcMonitor::Service.new.stop
  end
  
  opts.on("-u", "--update", "get update info") do
    updater = CcMonitor.update
    if(updater)
      puts <<-JSON
        {
          number: #{updater.latest_version},
          description: #{updater.latest_version_description},
          link: #{updater.latest_version_link}
        }
      JSON
    else
      puts "No update."
    end
  end
  
  opts.on_tail("-v", "--version", "Show version") do
    puts CcMonitor::VERSION
  end
end

if ARGV.empty?
  puts opts
end

CCM_LOGGER = Logger.new('runtime.log', 10, 1024000)
CCM_LOGGER.level = Logger::INFO
def logger
  CCM_LOGGER
end

begin
  opts.parse!
rescue Exception => e
  logger.error { e }
end
